package cn.ibobo.lease.common.util;

import net.coobird.thumbnailator.Thumbnails;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.util.*;
import java.util.List;

/**
 * @description 映射方式上传图片工具
 * @author lililiang
 * @date 2018/5/10 11:35
 * @param
 * @return
 */
public class UploadUtil {

    /**
     * @description 单个文件上传（使用路径映射方式）
     * @author lililiang
     * @date 2018/5/10 11:20
     * @param file,uploadPath, subPath]
     * @return boolean
     */
    public static String upLoadFile(MultipartFile file, String uploadPath, String subPath) throws IOException{
        String totalPath = uploadPath + subPath;
        String suffixName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        Long fileName = Calendar.getInstance().getTimeInMillis();
        //判断是否需要新建文件夹
        File d = new File(totalPath);
        if (!d.exists()) {
            d.mkdirs();
        }
        totalPath = totalPath + "/" + fileName + suffixName;
        Thumbnails.of(file.getInputStream()).scale(1f).toFile(totalPath);
        return subPath + "/" + fileName + suffixName;
    }

    /**
     * @description 多个文件上传（使用路径映射方式）
     * @author lililiang
     * @date 2018/5/10 11:20
     * @return boolean
     */
    public static List<String> upLoadFiles(MultipartFile[] files, String uploadPath, String subPath, String webPath)  throws IOException{
        List<String> imgPaths = new ArrayList<>();
        for (MultipartFile file : files){
            imgPaths.add(webPath + upLoadFile(file, uploadPath, subPath));
        }
        return imgPaths;
    }

    /**
     * @description 将File文件转换为MultipartFile（仅支持JPG格式)
     * @author lililiang
     * @date 2018/6/4 11:16
     * @return java.util.List<java.lang.String>
     */
    public static MultipartFile fileToMultipartFile(File file)  throws IOException{
        MockMultipartFile mockMultipartFile = new MockMultipartFile("copy.jpg","copy.jpg","image/jpeg", new FileInputStream(file));
        return mockMultipartFile;
    }


}
